package com.xupt.ttms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xupt.ttms.pojo.Comment;
import com.xupt.ttms.service.CommentService;
import com.xupt.ttms.mapper.CommentMapper;
import com.xupt.ttms.util.ThreadUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author 程康
* @description 针对表【t_comment】的数据库操作Service实现
* @createDate 2022-10-13 22:01:25
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean likeComment(Integer id) {
        Integer userID = ThreadUtils.getUserHolder().getId();
        String key = "comment:liked"+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userID.toString());
        boolean isSuccess;
        if (score == null) {
//        如果未点赞，可以点赞
            //数据库点赞数+1
            isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //保存用户到redis的set集合
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userID.toString(),System.currentTimeMillis());
            }
        }
        else {
//      如果已点赞，取消点赞
            //数据库点赞数-1
            isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            //把用户从redis的set集合移除
            if (isSuccess){
                stringRedisTemplate.opsForSet().remove(key,userID.toString(),System.currentTimeMillis());
            }
        }
        return isSuccess;
    }
}




